package com.shanghaionstar.service;

import android.content.Context;
import android.os.Environment;

import com.onstar.cn.api.PublicService;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.sqlite.entities.LandingsPageEntityNew;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by 7828wc on 2016/6/24.
 */
public class LandingPageService extends BaseService<LandingsPageEntityNew> {
    private Context context;
    private boolean isStop = false;
    private String downloadUrl = "";
    private String filePath = "";
    private LogManager log = LogManager.getInstance();
    private ResultListener resultListener;

    public LandingPageService(Context context) {
        this.context = context.getApplicationContext();
    }

    @Override
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public RequestEntity getRequestEntity() {
        PublicService publicService = new PublicService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getRequestEntity", requestEntity);
        return publicService.landingPage(requestEntity, FinalConstants.ANDROID_SMALL);
    }

    @Override
    public LandingsPageEntityNew jsonToBean(String json) {
        return GsonHelper.fromJson(json,LandingsPageEntityNew.class);
    }

    public void downloadImage(final LandingsPageEntityNew entity) {
        this.downloadUrl = entity.getImageURL();
        this.filePath = getFilePath();
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileOutputStream outStream = null;
                try {
                    URL url = new URL(downloadUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(6 * 1000);
                    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    if (conn.getResponseCode() == 200) {
                        InputStream inputStream = conn.getInputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            if (!isStop) {
                                outstream.write(buffer, 0, len);
                            }
                        }
                        // outstream.close();
                        inputStream.close();
                        byte[] data = outstream.toByteArray();
                        File file = new File(filePath + getFileName());
                        outStream = new FileOutputStream(file);
                        outStream.write(data);
                        outStream.close();
                        outStream.flush();
                        file = null;

                        entity.setStartTime(CommonUtil.formatDate(entity.getStartTime()) + "");
                        entity.setExpireTime(CommonUtil.formatDate(entity.getExpireTime()) + "");
                        entity.setFileName(getFileName());
                        entity.setFilePath(filePath + getFileName());
                        if(resultListener!=null) {
                            resultListener.onSuccess(entity);
                        }
                    } else {
                        if(resultListener!=null) {
                            resultListener.onError(null);
                        }
                    }
                } catch (Exception e) {
                    if(resultListener!=null) {
                        resultListener.onError(e);
                    }
                }finally {
                    if(outStream != null)
                        try {
                            outStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
        }).start();
    }

    public void setResultListener(ResultListener resultListener) {
        this.resultListener = resultListener;
    }
    public interface ResultListener{
        void onSuccess(LandingsPageEntityNew landingPage);

        void onError(Exception e);
    }

    public String getFileName() {
        String filename = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1, downloadUrl.length());
        if (CommonUtil.isNull(filename)) {
            log.d("filename is null,usage default filename");
            filename = "cache" + System.currentTimeMillis();
        }
        return filename + "_" + DeviceUtil.getLanguage();
    }

    public String getFilePath() {
        String filePath = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filePath = "/mnt/sdcard" + File.separator + "onstar";
        } else {
            filePath = context.getCacheDir().getAbsolutePath() + File.separator + "onstar";
        }
        filePath = filePath + File.separator + "cache" + File.separator;
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        log.d("File cache location :" + filePath);
        return filePath;
    }

    public void stop() {
        isStop = true;
    }
}
